const { getBlogList } = require('../api/blog');
const fs = require('fs');
const handleBlogDetail = require('./handleBlogDetail');

let page = 1;
const needDetailList = [];
const blogList = [];

const writeSourceList = () => {
  console.log(`已获取到${page}页共${blogList.length}条数据,将写入到本地中`);
  const toWriteList = blogList.sort((a, b) => b.created_at - a.created_at);
  fs.writeFileSync('./blog_list_source.json', JSON.stringify(toWriteList));
};

const randomToDo = (callback, coefficient = 8) => {
  const random = Math.random() * coefficient;
  console.log(`休息${random}s后继续获取`);
  setTimeout(callback, random * 1000);
};

const getBlogListReq = () => {
  console.log(`开始获取第${page}页`);
  getBlogList(page)
    .then(res => {
      const { list } = res.data;

      if (list.length) {
        list.forEach(item => {
          if (item.continue_tag) {
            // 需要获取到完整的微博内容,记录起来,待会儿一起处理
            needDetailList.push(item.mblogid);
            console.log(`微博[${item.mblogid}]需获取详情,已记录${needDetailList.length}条等待一并处理`);
          }
          blogList.push(item);
        });
        console.log(`第${page}页获取完毕,当前已经获取${blogList.length}条数据`);

        // 可能还有下一页
        page++;
        randomToDo(getBlogListReq);
      } else {
        console.log('已获取到该博主所有微博');
        writeSourceList();
        if (needDetailList.length) {
          console.log('有需要展开的内容,开始获取详细内容');
          // 写入到本地,自行处理
          fs.writeFileSync('./need_detail.json', JSON.stringify(needDetailList));
          handleBlogDetail();
        }
      }
    })
    .catch(err => {
      console.log(`获取第${page}页失败了`);
      writeSourceList();
      randomToDo(getBlogListReq);
    });
};

module.exports = { getBlogListReq };
